package com.demo.tool;

import android.util.Log;

import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class NetTool {

    /**
     * formatIpAddress 只能转化IPV4的IP地址  ;
     * String ipStr= Formatter.formatIpAddress(ipAddress) ;
     * ----------------
     * 这个方法有问题， 很多机型上显示  fe80::c486:e9ff:fe2d:4da1%p2p0 这种类型
     */
    @Deprecated
    public static String getHostIp() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> allAddress = intf.getInetAddresses(); allAddress.hasMoreElements(); ) {
                    InetAddress inetAddress = allAddress.nextElement();
                     /*-127.0.0.1
                     ----::1
                     ----192.168.1.115
                     ----fe80::c686:e9ff:fe2d:4da1%wlan0
                     ----fe80::c486:e9ff:fe2d:4da1%p2p0*/
                    boolean isIpV4V6 = (inetAddress instanceof Inet4Address) || (inetAddress instanceof Inet6Address);
                    boolean rightIp = (!inetAddress.isLoopbackAddress()) && isIpV4V6;//排除127.0.0.1

                    if (rightIp) {
                        return inetAddress.getHostAddress();
                    }
                    Log.i("aivin", "----" + inetAddress.getHostAddress());
                }
            }
        } catch (SocketException ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public static String getIpAddressString() {
        try {
            for (Enumeration<NetworkInterface> enNetI = NetworkInterface.getNetworkInterfaces(); enNetI.hasMoreElements(); ) {
                NetworkInterface netI = enNetI.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = netI.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (inetAddress instanceof Inet4Address && !inetAddress.isLoopbackAddress()) {
                        return inetAddress.getHostAddress();
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return "0.0.0.0";
    }
}

